import router from './router'
import store from './store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css'// Progress 进度条样式

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/auth/user/register', '/auth/user/resetpwd', '/404'] // 不重定向白名单

function hasPermission(roles, permissionRoles) {
  if (roles.indexOf('admin') >= 0 || roles.indexOf('system') >= 0) return true // admin permission passed directly
  if (!permissionRoles) return true
  return roles.some(role => permissionRoles.indexOf(role) >= 0)
}

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  if(!store.getters.equType){
    await store.dispatch('setEquType');
  }
  if (store.getters.token) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done() // if current page is dashboard will not trigger	afterEach hook, so manually handle it
    } else {
      // 判断当前用户是否已拉取完user_info信息
      if (!store.getters.user.username) {
        // 拉取user_info
        store.dispatch('GetInfo').then(res => {
          // res中包括roles[],根据roles权限生成可访问的路由表
          store.dispatch('GenerateRoutes', res).then((routers) => {
            // 动态添加可访问路由表
            // console.log('添加的路由：',store.getters.addRouters)
            for(const route of store.getters.addRouters){
              if(!route.path){
                console.log('path不存在:',route)
                for(const item of route ){
                  console.log(item.name)
                }
              }
            }
            router.addRoutes(store.getters.addRouters)
            // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
            next({ ...to, replace: true })
          })
        }).catch(() => {
          store.dispatch('FedLogOut').then(() => {
            next({ path: '/' })
          })
        })
      } else {
        // 没有动态改变权限的需求可直接next() 删除下方权限判断 ↓
        if (hasPermission(store.getters.roles, to.meta.roles)) {
          next()
        } else {
          next({ path: '/401', replace: true, query: { noGoBack: true }})
        }
        // 可删 ↑
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done() // 结束Progress
})
